<?php
namespace Drawping\Amap;

use GuzzleHttp\Client as HttpClient;

abstract class AbstractAPI
{
    protected $config = [];
    protected $http;
    protected $tableid;

    public function __construct($config)
    {
        $this->config = $config;
        $this->tableid = $config['tableid'];
        $this->http = new HttpClient();
    }

    public function signature($data){
        if(!$this->config['private_key']){
            return $data;
        }
        ksort($data);
        $data_form = [];
        foreach ($data as $key=>$value){
            $data_form[] = $key.'='.$value;
        }
        $data['sig'] = md5(implode('&', $data_form).$this->config['private_key']);
        return $data;
    }

    public function parseJSON($response)
    {
        if ($response->getStatusCode() !== 200) {
            throw new Exception("Amap: http error code ".(string)$response->getStatusCode());
        }

        $body = $this->fuckTheWeChatInvalidJSON($response->getBody());
        if (empty($body)) {
            throw new Exception("Amap: Can't find the content");
        }
        $contents = json_decode($body);

        if($contents->status != 1){
            throw new Exception("Amap: data status error");
        }
        return $contents;
    }

    /**
     * 设置地图id
     */
    public function setTableId($tableid){
        $this->tableid = $tableid;
    }

    protected function fuckTheWeChatInvalidJSON($invalidJSON)
    {
        return preg_replace('/[\x00-\x1F\x80-\x9F]/u', '', trim($invalidJSON));
    }
}